import { Logger } from '../../utils/logger';
import { BrowserUtils } from '~/utils/browser';

const SwaggerCache = new Map<string, any>();

/** 从Swagger URL中解析真实的API文档URL */
function extractSwaggerApiUrl(url: string) {
  try {
    const urlObj = new URL(url);
    const params = new URLSearchParams(urlObj.search);

    const operationId = urlObj.hash.split('/').slice(-1)[0];

    const tagName = urlObj.hash.split('/').slice(-2)[0];

    const apiUrl = params.get('url');

    if (!apiUrl || !operationId) {
      Logger.error(`无法从URL中提取API文档地址: ${url}`);
      return null;
    }

    return {
      apiUrl,
      operationId,
      tagName: decodeURIComponent(tagName),
    };
  } catch (error) {
    Logger.error(`解析Swagger URL失败: ${error}`);
    return null;
  }
}

function extractTagData(swaggerData: any, tagName: string): any {
  const result = {};

  Object.keys(swaggerData.paths || {}).forEach(path => {
    const info = swaggerData.paths[path];

    const data = info.get || info.post || info.put || info.delete || info.patch;

    if (data.tags.includes(tagName)) {
      const properties = data.responses.default?.content?.['application/json']?.schema?.properties;

      const schemasRef = properties?.data?.$ref;

      if (schemasRef) {
        const schemasName = schemasRef.replace('#/components/schemas/', '');

        const schemaData = swaggerData.components?.schemas[schemasName];

        properties.data = schemaData;
      }

      result[path] = data;
    }
  });

  return result;
}

/** 从Swagger页面中抓取API数据 */
export async function captureSwaggerDataFromUrl(url: string): Promise<any> {
  // 提取真实的API文档URL
  const { apiUrl, operationId, tagName } = extractSwaggerApiUrl(url);

  if (SwaggerCache.has(tagName)) {
    Logger.info(`使用缓存的Swagger数据: ${tagName}`);
    return JSON.parse(SwaggerCache.get(tagName));
  }

  const startTime = Date.now();

  try {
    if (!apiUrl) {
      throw new Error('无法提取API文档URL');
    }

    const result = await BrowserUtils.waitForApiData(url, apiUrl);

    Logger.info(`Swagger数据抓取成功: ${tagName + operationId} (${Date.now() - startTime}ms)`);

    const swaggerData = extractTagData(result.data, tagName);

    SwaggerCache.set(tagName, JSON.stringify(swaggerData));

    return swaggerData;
  } catch (error) {
    Logger.error(`Swagger数据抓取失败: ${error}`);
    throw error;
  }
}

/** 清理Swagger缓存 */
export function clearSwaggerCache(): void {
  SwaggerCache.clear();
  Logger.info('Swagger缓存已清理');
}
